from typing import List, Dict, Any
from sqlalchemy.orm.query import Query
from math import ceil

class Pagination:
    def __init__(self, query: Query, page: int = 1, per_page: int = 10):
        self.query = query
        self.page = max(1, page)  # 确保页码最小为1
        self.per_page = min(100, max(1, per_page))  # 限制每页数量在1-100之间
        self.total = query.count()
        
        # 计算总页数
        self.pages = ceil(self.total / self.per_page) if self.total > 0 else 0
        
        # 获取当前页数据
        self.items = query.offset((self.page - 1) * self.per_page).limit(self.per_page).all()

    def to_dict(self) -> Dict[str, Any]:
        return {
            'items': [item.to_dict() for item in self.items],
            'page': self.page,
            'per_page': self.per_page,
            'total': self.total,
            'pages': self.pages,
            'has_next': self.page < self.pages,
            'has_prev': self.page > 1
        }